package com.zhan.ielts.web.controller;

import com.google.common.io.Files;
import com.zhan.frame.core.dao.BaseService;
import com.zhan.frame.core.web.controller.BaseControllerImpl;
import com.zhan.ielts.domain.QAArticle;
import com.zhan.ielts.service.IQAArticleService;
import com.zhan.ielts.utils.StringUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tlfu on 2016/8/22.
 */
@Controller
@RequestMapping("/qa/article")
public class QAArticeController extends BaseControllerImpl<QAArticle, QAArticle> {
    private Logger log = LoggerFactory.getLogger(QAArticeController.class);
    @Autowired
    private IQAArticleService service;

    @Override
    protected BaseService<QAArticle> getBaseService() {
        return service;
    }

    @Override
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView selectList(QAArticle query, @PageableDefault Pageable pageable) {
        Page<QAArticle> page = getBaseService().queryPageList(query, pageable);
        ModelAndView mav = new ModelAndView("qa/articleList", "page", page);
        mav.addObject("query", query);
        return mav;
    }

    @RequestMapping(value = "editArticle", method = RequestMethod.POST)
    public ModelAndView editOne(QAArticle entity,HttpServletRequest request) {
        String content = entity.getContent();
        String str = entity.getUrl();
        File file = getHtmlData(content, str.substring(str.lastIndexOf("/") + 1, str.length() - 5),request);
        String htmlUrl = service.uploadFile(file);
        entity.setUrl(htmlUrl);
        entity.setUpdateTime(new Date());
        service.updateById(entity);
        return new ModelAndView("redirect:/qa/article");
    }

    @Override
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public ModelAndView editView(@PathVariable("id") String id) {
        QAArticle article = getBaseService().queryById(id);
        article.setContent(article.getContent().replaceAll("\"", "\\\\\"").replaceAll("[\r\n\t]", ""));
        return new ModelAndView("qa/articleEdit", path.getEntityName(), article);
    }

    @RequestMapping(value = "/preview", method = RequestMethod.POST)
    public ModelAndView preview(QAArticle entity,HttpServletRequest request) {
        String content = entity.getContent();
        File file = getHtmlData(content, null,request);
        StringBuilder sb = new StringBuilder();
        try {
            List<String> list = Files.readLines(file, Charset.forName("UTF-8"));
            if(!CollectionUtils.isEmpty(list)){
                for (String s : list) {
                    sb.append(s).append("\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        file.delete();
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("preContent",sb.toString());

        return new ModelAndView("qa/articlePre",model);
    }

    @RequestMapping(value = "/addArticle", method = RequestMethod.POST)
    public ModelAndView addArticle(QAArticle entity,HttpServletRequest request) {
        String content = entity.getContent();
        File file = getHtmlData(content, null,request);
        String htmlUrl = service.uploadFile(file);
        entity.setUrl(htmlUrl);
        entity.setCreatTime(new Date());
        entity.setUpdateTime(entity.getCreatTime());
        getBaseService().insert(entity);
        return new ModelAndView("redirect:/qa/article");
    }

    private File getHtmlData(String content, String uuId,HttpServletRequest request) {
        Configuration cfg = new Configuration();
        // cfg.setObjectWrapper(new DefaultObjectWrapper());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("kindEditorContent", content);
        map.put("base",request.getContextPath());
        try {
            String filePath = this.getClass().getClassLoader().getResource("").getPath();
            File file = new File(filePath);
            String modeFile = file.getParentFile().getParent() + File.separator + "resources" + File.separator;
            cfg.setTemplateLoader(new FileTemplateLoader(new File(modeFile)));
            if (uuId == null) {
                uuId = StringUtil.getUUIDRandom();
            }
            File out = new File(modeFile + uuId + ".html");
            if (out.exists()) {
                out.delete();
                out.createNewFile();
            }
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(modeFile + uuId + ".html", true), "UTF-8");
            Template template = cfg.getTemplate("IELTSQAModel.ftl");
            template.process(map, writer);
            writer.flush();
            writer.close();
            return out;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }

    @Override
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addView() {
        return new ModelAndView("qa/articleAdd");
    }


    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String uploadFile(@RequestParam(value = "imgFile", required = false) MultipartFile file) {
        JSONObject obj = new JSONObject();
        try {
            String filePath = service.uploadImage(file);
            obj.put("error", 0);
            obj.put("url", filePath);
        } catch (Exception e) {
            log.error(e.getMessage());
            obj.put("error", 1);
            obj.put("message", e.getMessage());
        }
        return obj.toString();
    }
}
